package com.bupt.service.common.impl;

import com.bupt.Factory.ProjectFactory;
import com.bupt.base.BaseDataSupport;
import com.bupt.basic.DemandReportService;
import com.bupt.basic.IBasicNetWork;
import com.bupt.basic.Project;
import com.bupt.config.interceptor.thread.CurrentUserInfo;
import com.bupt.dto.network.Node;
import com.bupt.dto.service.ServiceDto;
import com.bupt.dto.sys.UserDto;
import com.bupt.exception.BaseException;
import com.bupt.service.common.DemandService;
import com.bupt.utils.GenerateIDUtils;
import com.bupt.utils.LocalVerify;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.*;

@Service("demandService")
public class DemandServiceImpl implements DemandService {

    @Resource
    private JedisPool jedisPool;

    @Resource
    private CurrentUserInfo userInfo;

    protected String getServiceId() {
        return "S_" + BaseDataSupport.getCurrentDate() + "_" + GenerateIDUtils.getNumberStrByDate(jedisPool);
    }
    private static final Object lock = new Object();


    @Override
    public Object addDemand(UserDto userDto, String name, String sourceId, String targetId, Double rate, String layer, Integer year,
                           String type, String protect, Integer protectLimit, String projectId) throws BaseException {

        synchronized (lock) {
            userDto = userInfo.getCurrentOptUser();
            LocalVerify.verifyStringIsNotNull(name, sourceId, targetId, layer, type, projectId);
            // 校验公共的数据
            Project project = ProjectFactory.getObjectFromFile(projectId, ProjectFactory.storePath);
            List<DemandReportService> demandList = project.getDemandList();
            for (DemandReportService demandReportService : demandList) {
                if(demandReportService.getName().equals(name))throw new BaseException("业务名称已存在");
            }
            // 创建需求的对象
            IBasicNetWork.BasicNode fromNode = project.searchNodeById(sourceId);
            IBasicNetWork.BasicNode toNode = project.searchNodeById(targetId);
            if(fromNode==null)throw new BaseException("业务首节点不存在");
            if(toNode==null)throw new BaseException("业务末节点不存在");
            DemandReportService service = new DemandReportService(getServiceId(), name,
                    sourceId, targetId, type, rate, "", layer, year, new Date(), userDto.getUId(),
                    userDto.getUserName());

            service.setProtect(getProtect(protect));
            service.setProtectName(getProtect(protect));
            service.setProtectLimit(protectLimit);
            service.setNodeHeadName(fromNode.getName());
            service.setNodeTailName(toNode.getName());
            service.setBandwidthNum(rate);
            service.setBandwidth(rate+"");
            //添加业务
            demandList.add(service);
            updateProject(project);
            return getDemandsList(projectId);
        }
    }


    @Override
    public Object deleteDemand(UserDto userDto, String projectId, String demandId) throws BaseException {
        synchronized (lock) {
            LocalVerify.verifyStringIsNotNull(projectId, demandId);
            Project project = ProjectFactory.getObjectFromFile(projectId, ProjectFactory.storePath);
            List<DemandReportService> demandList = project.getDemandList();
            Iterator<DemandReportService> iterator = demandList.iterator();
            while(iterator.hasNext()){
                DemandReportService service = iterator.next();
                if(service.getId().equals(demandId)){
                    //删除业务
                    iterator.remove();
                    break;
                }
            }

            updateProject(project);
            return getDemandsList(projectId);
        }
    }

    @Override
    public Object updateDemand(UserDto userDto, String projectId, String demandId, String name, Double rate, String layer, Integer year, String type, String protect, Integer protectLimit) throws BaseException {
        synchronized (lock) {
            userDto = userInfo.getCurrentOptUser();
            LocalVerify.verifyStringIsNotNull(projectId, demandId, name, layer, type, protect);
            Project project = ProjectFactory.getObjectFromFile(projectId, ProjectFactory.storePath);
            List<DemandReportService> demandList = project.getDemandList();
            // String[] mustNodes = nodeMust.split(",");
            for (DemandReportService traffic : demandList) {
                if (traffic.getName().equals(name) && !traffic.getId().equals(demandId))
                    throw new BaseException("业务名称已存在");
            }
            for (DemandReportService traffic : demandList) {
                if (traffic.getId().equals(demandId)) {
                    traffic.getNodeMustArr().clear();
                    traffic.setName(name);
                    traffic.setBandwidthNum(rate);
                    traffic.setLayer(layer);
                    traffic.setYear(year);
                    /*for (String mustNode : mustNodes) {
                        traffic.getWorkMustNode().add(mustNode);
                    }*/
                    traffic.setType(type);
                    traffic.setProtect(getProtect(protect));
                    traffic.setProtectName(getProtect(protect));
                    traffic.setProtectLimit(protectLimit);
                }
            }

             updateProject(project);
            return getDemandsList(projectId);
        }
    }

    @Override
    public Object getDemandsList(UserDto userDto, String projectId) throws BaseException {
        synchronized (lock) {
            LocalVerify.verifyString(projectId,"项目id");
            return getDemandsList(projectId);
        }
    }
   @Override
    public List<ServiceDto> getDemandsList(String projectId)throws BaseException{
        Project project = ProjectFactory.getObjectFromFile(projectId, ProjectFactory.storePath);
       List<DemandReportService> demandList = project.getDemandList();
       ArrayList<ServiceDto> trafficDtos = new ArrayList<>();
        for (DemandReportService demandReportService : demandList) {
            List<Node> node = getNode(demandReportService.getNodeHead(), demandReportService.getNodeTail(), project);

            ServiceDto serviceDto = new ServiceDto(demandReportService.getId(), demandReportService.getName(), node.get(0), node.get(1), demandReportService.getYear(), demandReportService.getBandwidthNum(),
                    demandReportService.getType(), demandReportService.getLayer(), demandReportService.getProtect(), demandReportService.getProtectLimit(),
                    "".split(","),demandReportService.getStatus(),demandReportService.getReason());
            trafficDtos.add(serviceDto);
        }
        return trafficDtos;

    }


    private void updateProject(Project project) throws BaseException {
        boolean b = ProjectFactory.saveObjectDataToFile(project, project.getId(), ProjectFactory.storePath);
        if (!b) throw new BaseException("文件固化失败");
    }

    private List<Node> getNode(String sourceNodeId,String targetNodeId,Project project){
        List<Node> nodeList = new ArrayList<>();
        IBasicNetWork.BasicNode fromNode = project.searchNodeById(sourceNodeId);
        IBasicNetWork.BasicNode toNode = project.searchNodeById(targetNodeId);
        Node node1 = new Node(fromNode.getNodeId(), fromNode.getName(), fromNode.getPointX(), fromNode.getPointY());
        Node node2 = new Node(toNode.getNodeId(), toNode.getName(), toNode.getPointX(), toNode.getPointY());
        nodeList.add(node1);
        nodeList.add(node2);
        return nodeList;
    }

    private String getProtect(String protect){
        switch (protect){
            case "NORMAL":
                return "无保护";
            case "RESTORATION":
                return "重路由";
            case "RESTORATION11":
                return "1+1+重路由";
            case "PERMANENT11":
                return "永久1+1";
            case "NORMAL11":
                return "1+1";
            case "无保护":
                return "无保护";
            case "重路由":
                return "重路由";
            case "1+1+重路由":
                return "1+1+重路由";
            case "永久1+1":
                return "永久1+1";
            case "1+1":
                return "1+1";
        }
          return "";
    }
}
